package org.mspring.mlog.web.module.admin.spider;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.mspring.mlog.api.spider.Spider;
import org.mspring.mlog.api.spider.crawler.DefaultCrawler;
import org.mspring.mlog.api.spider.entity.SpiderRule;
import org.mspring.mlog.api.spider.service.SpiderPostService;
import org.mspring.mlog.api.spider.service.SpiderRuleService;
import org.mspring.mlog.api.spider.utils.DocumentUtils;
import org.mspring.mlog.web.support.log.Log;
import org.mspring.platform.dao.Order.OrderType;
import org.mspring.platform.dao.Page;
import org.mspring.platform.dao.query.QueryBuilder;
import org.mspring.platform.utils.RequestUtils;
import org.mspring.platform.web.ResponseEntity;
import org.mspring.platform.web.freemarker.widget.stereotype.Widget;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 *
 * @author Gao Youbo
 * @since 1994-4-14
 */
@Widget
@RequestMapping("/admin/spider/rule")
public class Admin_SpiderRuleWidget extends AbstractSpiderWidget {

    @Autowired
    private SpiderRuleService spiderRuleService;
    @Autowired
    private SpiderPostService spiderPostService;

    @RequestMapping("/list")
    @Log
    public String list(@ModelAttribute Page<SpiderRule> rulePage, @ModelAttribute SpiderRule spiderRule, @RequestParam Map<String, Object> queryParams, HttpServletRequest request, HttpServletResponse response, Model model) {
        if (rulePage == null) {
            rulePage = new Page<>();
        }
        rulePage.addOrder("id", OrderType.DESC);
        rulePage = spiderRuleService.listPage(QueryBuilder.instance(SpiderRule.class, queryParams), rulePage);
        model.addAttribute("rulePage", rulePage);
        return "/admin/spider/rule/listRule";
    }

    @RequestMapping("/create")
    public String create_view(@ModelAttribute SpiderRule spiderRule, HttpServletRequest request, HttpServletResponse response, Model model) {
        Map<String, String> enabled = new HashMap<>();
        enabled.put("true", "是");
        enabled.put("false", "否");
        model.addAttribute("enabled", enabled);
        return "/admin/spider/rule/createRule";
    }

    @RequestMapping("/create/save")
    @Log
    public String create_save(@ModelAttribute SpiderRule spiderRule, HttpServletRequest request, HttpServletResponse response, Model model) {
        spiderRuleService.create(spiderRule);
        return prompt(model, "系统提示", "规则创建成功", "/admin/spider/rule/list");
    }

    @RequestMapping("/edit")
    public String edit_view(@RequestParam(required = false) Long id, @ModelAttribute SpiderRule spiderRule, HttpServletRequest request, HttpServletResponse response, Model model) {
        if (id == null) {
            Object obj = getSessionAttribute(request, "SpiderRuleWidget_edit_id");
            if (obj != null) {
                id = (Long) obj;
            }
        }
        if (id == null) {
            return prompt(model, "请先选择要修改的规则");
        }

        spiderRule = spiderRuleService.get(id);
        if (spiderRule == null) {
            return prompt(model, "请先选择要修改的规则");
        }
        Map<String, String> enabled = new HashMap<>();
        enabled.put("true", "是");
        enabled.put("false", "否");
        model.addAttribute("enabled", enabled);
        model.addAttribute("spiderRule", spiderRule);
        setSessionAttribute(request, "SpiderRuleWidget_edit_id", id);
        return "/admin/spider/rule/editRule";
    }

    @RequestMapping("/edit/save")
    @Log
    public String edit_save(@RequestParam(required = false) Long id, @ModelAttribute SpiderRule rule, HttpServletRequest request, HttpServletResponse response, Model model) {
        spiderRuleService.update(rule);
        return prompt(model, "系统提示", "规则修改成功", "/admin/spider/rule/list");
    }

    /**
     * 测试采集URL列表
     *
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping("/test/urllist")
    @ResponseBody
    public ResponseEntity test_urlList(HttpServletRequest request, HttpServletResponse response, Model model) {
        ResponseEntity rsp = new ResponseEntity();
        try {
            String testListURL = RequestUtils.getRequestParameterAsString(request, "testListURL");
            String listRule = RequestUtils.getRequestParameterAsString(request, "listRule");

            SpiderRule rule = new SpiderRule();
            rule.setListRule(listRule);

            Spider spider = new Spider(new DefaultCrawler());

            Document doc = DocumentUtils.getDocument(testListURL);
            List<String> urls = spider.getUrls(doc, rule);

            rsp.setSuccess(true);
            rsp.put("urls", urls);
            return rsp;
        } catch (Exception e) {
            rsp.setSuccess(false);
            rsp.setMessage(e.getMessage());
            return rsp;
        }
    }

    /**
     * 测试正文内容
     *
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping("/test/content")
    @ResponseBody
    public ResponseEntity test_content(HttpServletRequest request, HttpServletResponse response, Model model) {
        ResponseEntity rsp = new ResponseEntity();
        try {
            String testContentURL = RequestUtils.getRequestParameterAsString(request, "testContentURL");
            String titleRule = RequestUtils.getRequestParameterAsString(request, "titleRule");
            String contentRule = RequestUtils.getRequestParameterAsString(request, "contentRule");

            SpiderRule rule = new SpiderRule();
            rule.setTitleRule(titleRule);
            rule.setContentRule(contentRule);
            Spider spider = new Spider(new DefaultCrawler());

            Document doc = DocumentUtils.getDocument(testContentURL);
            String title = spider.getTitle(doc, rule);
            Element content = spider.getContent(doc, rule);

            if (title != null) {
                rsp.put("title", title);
            }
            if (content != null) {
                rsp.put("content", content.children().outerHtml());
            }
            rsp.setSuccess(true);
            return rsp;
        } catch (Exception e) {
            e.printStackTrace();
            rsp.setSuccess(false);
            rsp.setMessage(e.getMessage());
            return rsp;
        }
    }
}
